import React, { useRef, useEffect, useState } from 'react';
import { ChinaMapStyled } from './styles';

import * as echarts from 'echarts';
import { chinaMapConfig } from './config';
import { geoJson } from './geojson';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import { MainState } from '@/store/reducers/main';

const ChinaMap = () => {
  const { allData } = useSelector<RootState, MainState>((state) => state.main);
  const [data, setData] = useState<any>([]);
  useEffect(() => {
    allData?.sectLocal &&
      setData(allData.sectLocal.map((item) => ({ name: item.name.split('市')[0], value: item.number })));
  }, [allData]);
  const chartRef = useRef(null);
  let mapInstance: any = null;

  const renderMap = () => {
    if (chartRef.current) {
      const renderMapInstance = echarts.getInstanceByDom(chartRef.current);
      if (renderMapInstance) {
        mapInstance = renderMapInstance;
      } else {
        mapInstance = echarts.init(chartRef.current);
      }
      mapInstance.setOption(
        chinaMapConfig({
          data,
          max: 99,
          min: 0,
        }),
      );
    }
  };

  useEffect(() => {
    //@ts-ignore
    echarts.registerMap('china', { geoJSON: geoJson });
    renderMap();
  }, [data]);

  useEffect(() => {
    window.onresize = function () {
      mapInstance.resize();
    };
    return () => {
      mapInstance && mapInstance.dispose();
    };
  }, []);

  return (
    <ChinaMapStyled>
      <div ref={chartRef} style={{ width: '100%', height: '100%' }}></div>
    </ChinaMapStyled>
  );
};

export default ChinaMap;
